
#import "GetTorrentFileListRequest.h"

@implementation GetTorrentFileListRequest

//
// torrent id
//
@synthesize torrentId														= _torrentId;

//
// file list
//
@synthesize fileList														= _fileList;

//
// init
//
- (id)init
{
	//
	// call super
	//
	self																	= [super init];
	if(!self)
		return nil;
	
	//
	// create xml parser, file list
	//
	self.xmlParser															= [[[XmlParser alloc] init] autorelease];
	self.fileList															= [NSMutableArray arrayWithCapacity:10];
	
	return self;
}

//
// dealloc
//
- (void)dealloc
{
	self.fileList															= nil;
	
	[super dealloc];
}

//
// setup request
//
- (void)setupRequest
{
	//
	// setup relpath
	//
	self.relPath															= [NSString stringWithFormat:@"viewfilelist.php?id=%d", self.torrentId];
	
	//
	// call super
	//
	[super setupRequest];
}

//
// finished
//
- (void)connectionDidFinishLoading:(NSURLConnection*)connection
{
	if(self.response.statusCode == 200)
	{
		NSMutableData* fullData												= [NSMutableData dataWithData:self.dataBuffer];
		static char const* header											= "<html xmlns=\"http://www.w3.org/1999/xhtml\"> <head> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"> </head><body>";
		static char const* footer											= "</body></html>";
		[fullData replaceBytesInRange:NSMakeRange(0, 0) withBytes:header length:strlen(header)];
		[fullData appendBytes:footer length:strlen(footer)];
		
		[self.xmlParser parseDocumentData:fullData htmlMode:YES];
		
		NSArray* fileRows													= [self.xmlParser nodesFromPath:@"//table[@class='main']/tr[position()>1]" startNode:0];
		for(NSValue* rowValue in fileRows)
		{
			@autoreleasepool
			{
				TorrentFileInfo* info										= [[[TorrentFileInfo alloc] init] autorelease];
				info.fileName												= [self.xmlParser stringFromPath:@"./td[1]" startNode:(xmlNodePtr)[rowValue pointerValue]];
				info.fileSize												= [self.xmlParser stringFromPath:@"./td[2]" startNode:(xmlNodePtr)[rowValue pointerValue]];
				[self.fileList addObject:info];
			}
		}
	}
	
	[super connectionDidFinishLoading:connection];
}

@end
